package com.example.demo.services.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.example.demo.dao.Role_permissionMapper;
import com.example.demo.domain.Role_permission;
import com.example.demo.domain.Sys_permission;
import com.example.demo.services.Role_permissionService;

import net.sf.json.JSONObject;


@Service
@Repository
public class Role_permissionServiceImpl implements Role_permissionService {
	
	@Autowired
	private Role_permissionMapper role_permissionMapper;

	
	/**
	 * 	根据角色ID查询所有此角色拥有的权限ID
	 * @param roleId
	 * @return
	 */
	@Override
	public List<Integer> getPermissionIdByRoleId(int roleId) {
		List<Integer> permissionId = role_permissionMapper.queryPermissionIdByRoleId(roleId);
		return permissionId;
	}

	
	
	/**
	 *       保存角色的权限 
	 * @param map
	 * @return
	 */
	@Override
	public int savePermissionByRoleId(Map map) {
		int role_id = Integer.parseInt(map.get("role_id").toString());
		List permission = (List) map.get("permission");
		Role_permission role_permission = new Role_permission();
		int result = 0;
		System.out.println(permission.toString());
		if(map.get("moduleId") == "" && map.get("menuId") == "") {
			role_permissionMapper.deletePermissionByRoleId(role_id);
		}else if(map.get("moduleId") != ""){
			role_permissionMapper.deletePermissionByModuleId(Integer.parseInt(map.get("moduleId").toString()), role_id);
		}else {
			role_permissionMapper.deletePermissionByMenuId(Integer.parseInt(map.get("menuId").toString()), role_id);
		}
		if(permission.size() > 0) {
			for(int i = 0; i < permission.size(); i++) {
				JSONObject obj = (JSONObject) permission.get(i);
				role_permission.setRole_id(role_id);
				role_permission.setPermission_id(Integer.parseInt(obj.get("id").toString()));
				result = role_permissionMapper.insert(role_permission);
			}	
		}else {
			result = 1;
		}
		return result;
	}

}
